package com.example.cadmin.utils.Netty;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.util.HashMap;
import java.util.Map;

/**
 * 客户端，发送命令
 */
@Slf4j
@Component
public class Client {
    public String send(String content, String ip) throws IOException {
        String[] ipList = ip.split(":");
        synchronized(this) {
            String result = null;
            try {
                Socket client = new Socket();
                client.connect(new InetSocketAddress(ipList[0], Convert.toInt(ipList[1])), 3000);
                client.setSoTimeout(3000);
                //获取Socket的输出流，用来发送数据到服务端
                OutputStream out = client.getOutputStream();
                //获取Socket的输入流，用来接收从服务端发送过来的数据
                InputStream buf = client.getInputStream();
                //发送数据到服务端
                log.info("发送数据："+content);
                byte[] temp = content.getBytes("gbk");//这里写原编码方式
                out.write(temp);
                byte[] bytes = new byte[1024];
                int len = buf.read(bytes);
                result = new String(bytes, 0, len, "gbk");
                out.flush();
                Thread.sleep(200);
                buf.close();
                out.close();
                client.close();
            } catch (SocketTimeoutException e) {
                log.info("连接超时");
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            log.info("接收数据："+result);
            return result;
        }
    }

    public static void main(String[] args) throws IOException, InterruptedException {
        TimeInterval timer = DateUtil.timer();
        String ip = "192.168.0.11:8234";

        Map<String, Object> map = new HashMap<>();
        map.put("device","server");
        map.put("from",0);
        map.put("to",Convert.toInt(0));
        map.put("cmd","motor_ctrl");
        map.put("params","forward");
        String sendMap = JSONUtil.toJsonStr(map);
        String rfidResult = new Client().send(sendMap, ip);
        JSONObject rfidObject = JSONUtil.parseObj(rfidResult);
        System.out.println(rfidObject);
        Thread.sleep(200);
    }
}
